//
// Created by chizuru on 2025/9/29.
//

#pragma once
#include "ProtocolResult.h"
#include "IProtocolCodec.h"
#include <vector>
#include <cstdint>
#include <string>
#include <optional>

class ModBusProtocolCodec :public IProtocolCodec{
public:
    std::vector<uint8_t> buildWriteFrame(const CommandId &id, const CodecArgs &args) const override;

    std::vector<uint8_t> buildReadFrame(const CommandId &id, const CodecArgs &args) const override;

    ProtocolResult parseWriteResponse(std::span<const uint8_t> resp, const CommandId &commandId, const CodecArgs& args) const override;

    ProtocolResult parseReadResponse(std::span<const uint8_t> resp, const CommandId &commandId, const CodecArgs& args) const override;

private:
    // CRC16 (Modbus) 表在第一次调用时生成（线程安全的静态局部变量）
    static const std::array<uint16_t, 256>& get_crc16_table();

    static uint16_t crc16_modbus(const uint8_t* data, size_t length);
};
